<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\ScoreRuleController;
use App\Models\ContestActivity;
use App\Models\ContestActivityType;
use App\Models\ContestActivityUnit;
use App\Models\ContestActivityVote;
use App\Models\ContestActivityWorks;
use App\Models\UserInfo;
use App\Models\UserViolate;
use App\Validate\ContestActivityValidate;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 线上大赛活动
 * Class ContestActivityType
 * @package app\admin\controller
 */
class ContestActivityController extends CommonController
{
    public $model = null;
    public $validate = null;
    public $worksModel = null;
    public $score_type = 7;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ContestActivity();
        $this->validate = new ContestActivityValidate();
        $this->worksModel = new ContestActivityWorks();
    }

    /**
     * 图书馆列表(用于下拉框选择)
     * @param con_id 大赛id
     */
    public function getLibName()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_filter_unit_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //判断是否是单位联盟大赛
        $contestActivityUnitModel = new ContestActivityUnit();
        $isAllowAddUnit = $contestActivityUnitModel->isAllowAddUnit($this->request->con_id);
        if ($isAllowAddUnit !== true) {
            return $this->returnApi(202, $isAllowAddUnit);
        }

        $res = $contestActivityUnitModel->select(['id', 'con_id', 'name', 'originals'])
            ->where('con_id', $this->request->con_id)
            ->where('is_del', 1)
            ->orderBy('order')
            ->get();
        if (empty($res)) {
            return $this->returnApi(203, '暂无数据');
        }
        $originals = '';
        foreach ($res as $key => $val) {
            if (empty($val['originals'])) {
                if (empty($originals)) {
                    $originals =  $this->model->where('id', $this->request->con_id)->value('originals');
                }
                $res[$key]['originals'] = $originals;
            }
        }

        return $this->returnApi(200, "查询成功", true, $res);
    }


    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param node int 0 全部 举办方式   1 独立活动  2 多馆联合   
     * @param keywords string 搜索关键词(文章标题)
     * @param start_time datetime 比赛开始时间(开始)
     * @param end_time datetime 比赛截止时间(截止)
     */
    public function lists()
    {
        $page = request()->page ? intval(request()->page) : 1;
        $limit = request()->limit ? intval(request()->limit) : 10;
        $node = request()->node;
        $keywords = request()->keywords;
        $start_time = request()->start_time;
        $end_time = request()->end_time;

        $res = $this->model->lists($node, $keywords, $start_time, $end_time, null, null, 1, $limit);

        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(28);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['take_number'] = $this->worksModel->getTakeNumber($val['id']); //参与人数
            $res['data'][$key]['status'] = $this->model->getContestStatus($val); //获取活动状态
            $res['data'][$key]['con_start_time'] = date('Y-m-d H:i', strtotime($val['con_start_time']));
            $res['data'][$key]['con_end_time'] = date('Y-m-d H:i', strtotime($val['con_end_time']));
        }

        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }
    /**
     * 我的大赛列表
     * @param token 用户token
     * @param page int 当前页
     * @param limit int 分页大小
     * @param node int 0 全部 举办方式   1 独立活动  2 多馆联合   
     * @param keywords string 搜索关键词(文章标题)
     * @param start_time datetime 比赛开始时间(开始)
     * @param end_time datetime 比赛截止时间(截止)
     */
    public function myContestLists()
    {
        $page = request()->page ? intval(request()->page) : 1;
        $limit = request()->limit ? intval(request()->limit) : 10;
        $keywords = request()->keywords;
        $node = request()->node;
        $start_time = request()->start_time;
        $end_time = request()->end_time;
        $user_id = $this->request->user_info['id'];

        $res = $this->model->myContestLists($node, $user_id, $keywords, $start_time, $end_time, 1, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['take_number'] = $this->worksModel->getTakeNumber($val['id']); //参与人数
            $res['data'][$key]['status'] = $this->model->getContestStatus($val); //获取活动状态
        }

        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param token 用户token
     * @param id int 比赛id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $res = $this->model->select(
            'id',
            'node',
            'title',
            'app_img as img',
            'host_handle',
            'tel',
            'con_start_time',
            'con_end_time',
            'vote_start_time',
            'vote_end_time',
            'is_reader',
            'vote_way',
            'number',
            'originals',
            'real_info',
            'intro',
            'rule_content',
            'create_time'
        )->find($this->request->id);

        if (empty($res)) {
            return $this->returnApi(202, '参数传递错误');
        }

        $res->status = $this->model->getContestStatus($res); //获取活动状态
        $res->take_number = $this->worksModel->getTakeNumber($res['id']); //参与人数

        $contestActivityVoteObj = new ContestActivityVote();
        list($res->vote_msg, $res->vote_number) = $contestActivityVoteObj->getVoteNum($res->vote_way, $res->number, $user_id, $this->request->id);


        //更新浏览量
        $this->model->updateBrowseNumber($this->request->id);

        $res = $res->toArray();
        // if ($res['real_info']) {
        //     $real_info = explode("|", $res['real_info']);
        //     $real_info_arr = $this->model->getContestActivityApplyParam(); //获取所有的数据
        //     $res['real_info'] = [];
        //     foreach ($real_info as $key => $val) {
        //         foreach ($real_info_arr as $k => $v) {
        //             if ($val == $v['id']) {
        //                 $res['real_info'][] = $v;
        //                 continue;
        //             }
        //         }
        //     }
        // } else {
        //     $res['real_info'] = [];
        // }

        $real_info_arr = $this->model->getContestActivityApplyParam(); //获取所有的数据
        $res['real_info'] = $this->getRealInfoArray($res['real_info'], $real_info_arr);
        $res['con_start_time'] = date('Y-m-d H:i', strtotime($res['con_start_time']));
        $res['con_end_time'] = date('Y-m-d H:i', strtotime($res['con_end_time']));
        $res['vote_start_time'] = date('Y-m-d H:i', strtotime($res['vote_start_time']));
        $res['vote_end_time'] = date('Y-m-d H:i', strtotime($res['vote_end_time']));

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 参赛作品列表
     * @param token 用户token
     * @param con_id 大赛id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param type_id int 类型id
     * @param sort int 排序方式  1 时间排序（默认）  2 投票排序
     * @param keywords string 搜索关键词(名称)
     * @param except_ids string 需要排除的id ，多个逗号链接
     */
    public function productionList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_production_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $con_id = $this->request->con_id;
        $type_id = $this->request->type_id;
        $sort = $this->request->sort;
        $keywords = $this->request->keywords;
        $except_ids = $this->request->except_ids;
        $limit = $this->request->input('limit', 10);

        $sort = $sort == 2 ? 'vote_num DESC,id DESC' : 'id DESC';
        $res = $this->worksModel->lists($con_id, null, null, $type_id, $keywords, ['1'], $except_ids, null, null, $sort, $limit);


        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $contestActivityVoteObj = new ContestActivityVote();
        $data = $this->model->where('id', $con_id)->where('is_del', 1)->where('is_play', 1)->first();
        if (empty($data)) {
            return $this->returnApi(203, "暂无数据");
        }
        $vote_way = $data['vote_way'];

        foreach ($res['data'] as $key => $val) {
            if ($user_id) {
                $res['data'][$key]['user_vote_num'] = $contestActivityVoteObj->userVoteNum($vote_way, $user_id, $con_id, $val['id']); //用户投票数
            } else {
                $res['data'][$key]['user_vote_num'] = 0; //获取活动状态
            }
        }

        $contestActivity = ContestActivity::select('id', 'vote_way', 'number', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time')->where('id', $con_id)->first();
        list($contestActivity->vote_msg, $contestActivity->vote_number) = $contestActivityVoteObj->getVoteNum($contestActivity->vote_way, $contestActivity->number, $user_id, $con_id);
        $res = $this->disPageData($res);
        $res['contest_activity'] = $contestActivity;
        $res['contest_activity']['status'] = $this->model->getContestStatus($data); //获取活动状态

        return $this->returnApi(200, "获取成功", true, $res);
    }


    /**
     * 我的参赛作品列表
     * @param token 用户token
     * @param con_id 大赛id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param type_id int 类型id
     * @param sort int 排序方式  1 时间排序（默认）  2 投票排序
     * @param keywords string 搜索关键词(名称)
     */
    public function myProductionList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_production_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $con_id = $this->request->con_id;
        $type_id = $this->request->type_id;
        $sort = $this->request->sort;
        $keywords = $this->request->keywords;
        $limit = $this->request->input('limit', 10);

        $sort = $sort == 2 ? 'vote_num DESC,id DESC' : 'id DESC'; //vote_num ASC,id ASC 解决点赞量全为0时，数据错乱问题
        $res = $this->worksModel->lists($con_id, null, $user_id, $type_id, $keywords, ['1', '2', '3', '4'], '', null, null, $sort, $limit);


        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $contestActivityVoteObj = new ContestActivityVote();
        $data = $this->model->where('id', $con_id)->first();
        $vote_way = $data['vote_way'];

        foreach ($res['data'] as $key => $val) {
            if ($user_id) {
                $res['data'][$key]['user_vote_num'] = $contestActivityVoteObj->userVoteNum($vote_way, $user_id, $con_id, $val['id']); //用户投票数
            } else {
                $res['data'][$key]['user_vote_num'] = 0; //获取活动状态
            }
        }

        $contestActivity = ContestActivity::select('id', 'vote_way', 'number', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time')->where('id', $con_id)->first();
        //文案、可投票量
        list($contestActivity->vote_msg, $contestActivity->vote_number) = $contestActivityVoteObj->getVoteNum($contestActivity->vote_way, $contestActivity->number, $user_id, $con_id);
        $res = $this->disPageData($res);

        $res['contest_activity'] = $contestActivity;
        $res['contest_activity']['status'] = $this->model->getContestStatus($data); //获取活动状态

        return $this->returnApi(200, "获取成功", true, $res);
    }


    /**
     * 参赛作品详情+我的作品详情
     * @param token 用户token
     * @param id id
     * @param way 请求方式   1  前台个人中心查看 ；其他为其他界面
     */
    public function productionDetail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_production_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $way = $this->request->way;
        $user_id = $this->request->user_info['id'];

        $res = $this->worksModel
            ->select(
                'id',
                'unit_id',
                'con_id',
                'serial_number',
                'username',
                'tel',
                'id_card',
                'user_id',
                'unit',
                'wechat_number',
                'adviser',
                'adviser_tel',
                'reader_id',
                'title',
                'type_id',
                'img',
                'content',
                'voice',
                'voice_name',
                'video',
                'video_name',
                'intro',
                'cover',
                'width',
                'height',
                'browse_num',
                'vote_num',
                'status',
                'reason',
                'is_violate',
                'violate_reason',
                'violate_time',
                'create_time',
                'change_time'
            )
            ->with(['conType' => function ($query) {
                $query->select('id', 'type_name', 'limit_num', 'letter', 'node');
            }])
            ->find($this->request->id);

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }

        //其他界面不能查看未审核的作品
        if ($way != 1 && $res['status'] != 1) {
            return $this->returnApi(203, "暂无数据");
        }

        //增加访问量
        if ($way != 1) {
            $res->browse_num = ++$res->browse_num;
            $res->save();
        }

        $contestActivityUnitModel = new ContestActivityUnit();
        $res['unit_name'] = $contestActivityUnitModel->getUnitNameByUnitId($res['unit_id']);

        $contestActivityVoteObj = new ContestActivityVote();
        $vote_way = $this->model->where('id', $res['con_id'])->value('vote_way');
        if ($user_id) {
            $res['user_vote_num'] = $contestActivityVoteObj->userVoteNum($vote_way, $user_id, $res->con_id, $res['id']); //用户投票数
        } else {
            $res['user_vote_num'] = 0; //获取活动状态
        }

        $contestActivity = ContestActivity::select('id', 'vote_way', 'number', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time')->where('id', $res->con_id)->first();
        list($contestActivity->vote_msg, $contestActivity->vote_number) = $contestActivityVoteObj->getVoteNum($contestActivity->vote_way, $contestActivity->number, $user_id, $res->con_id);
        $res['contest_activity'] = $contestActivity;

        $res['head_img'] = UserInfo::getWechatField($res->user_id, 'head_img');

        return $this->returnApi(200, "获取成功", true, $res);
    }

    /**
     * 线上大赛类型
     * @param token 用户token
     * @param con_id  大赛id
     */
    public function getTypeList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_type_list')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];

        $contestActivityTypeObj = new ContestActivityType();
        $res = $contestActivityTypeObj->select(['id', 'type_name', 'limit_num', 'letter', 'node'])
            ->where('con_id', $this->request->con_id)
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->get();

        if ($res->isEmpty()) {
            return $this->returnApi(203, "暂无数据");
        }
        foreach ($res as $key => $val) {
            $res[$key]->have_number = $this->worksModel->getUserWorksNumberByTypeId($this->request->con_id, $user_id, $val['id']);
        }

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }
    /**
     * 根据电话号码获取用户基本信息
     * @param tel  电话号码
     */
    public function getWorksUserInfo()
    {

        //增加验证场景进行验证
        if (!$this->validate->scene('wx_works_user_info')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        $res = $this->worksModel->select(['tel', 'username', 'id_card', 'unit', 'wechat_number', 'adviser', 'adviser_tel', 'reader_id'])
            ->where('tel', $this->request->tel)
            ->where('user_id', $user_id)
            ->orderByDesc('id') //获取最新的
            ->first();

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }

    /**
     * 作品投票
     * @param token  用户token
     * @param works_id 作品id
     */
    public function  worksVote()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_works_vote')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];


        Log::info(date('Y-m-d H:i:s') . '~用户id：' . $user_id . '；作品id：' . $this->request->works_id . ';ip地址：' . request()->ip());

        // $ip = [
        //     '112.98.169.75',
        //     '222.180.68.57',
        //     '223.104.251.49',
        //     '183.230.215.93',
        // ];
        // if(in_array(request()->ip() , $ip)){
        //     return $this->returnApi(201, "系统检测到你存在刷票行为，暂时取消你的投票资格");
        // }

        //限制用户多次点击
        $key = md5($user_id . $this->request->works_id . request()->ip());

        $oldKey =  Cache::get($key); //没有缓存返回false
        if ($oldKey) {
            return $this->returnApi(201, "您操作的太频繁了，请稍后重试");
        } else {
            Cache::put($key, 1, 10);
        }


        $worksInfo = $this->worksModel->find($this->request->works_id);
        if (empty($worksInfo)) {
            return $this->returnApi(201, "参数错误");
        }
        if ($worksInfo['status'] != 1) {
            Log::info('当前作品未审核通过，不允许投票-' . date('Y-m-d H:i:s') . '~用户id：' . $user_id . '；作品id：' . $this->request->works_id . ';ip地址：' . request()->ip());

            return $this->returnApi(201, "当前作品未审核通过，不允许投票");
        }

        $contestInfo = $this->model->select('id', 'vote_way', 'number', 'vote_start_time', 'vote_end_time')->where('is_del', 1)->find($worksInfo['con_id']);
        if (empty($contestInfo)) {
            return $this->returnApi(201, "参数错误");
        }
        if ($contestInfo['vote_way'] == 3) {
            return $this->returnApi(201, "此活动无需投票");
        }
        if ($contestInfo['vote_start_time'] > date('Y-m-d H:i:s')) {
            return $this->returnApi(201, "投票未开始，暂不允许投票");
        }
        if ($contestInfo['vote_end_time'] < date('Y-m-d H:i:s')) {
            return $this->returnApi(201, "投票已结束，不允许投票");
        }

        $contestActivityVoteObj = new ContestActivityVote();
        if ($contestInfo['vote_way'] == 1) {
            //查看用户共投了好多票
            $user_vote_num = $contestActivityVoteObj->getVoteNumber($user_id, $contestInfo['id']); //用户投票数量

            if ($contestInfo['number'] !== 0 && $contestInfo['number'] <= $user_vote_num) {
                return $this->returnApi(202, "投票次数已达到上限");
            }
        } else {
            $user_vote_num = $contestActivityVoteObj->getVoteNumber($user_id, $contestInfo['id'], null, date('Y-m-d')); //用户投票数量

            if ($contestInfo['number'] !== 0 && $contestInfo['number'] <= $user_vote_num) {
                return $this->returnApi(202, "今日投票次数已达到上限，请明日再来！");
            }
        }

        DB::beginTransaction();
        try {
            $worksInfo->vote_num = ++$worksInfo->vote_num;
            $worksInfo->save();

            $contestActivityVoteObj->add([
                'con_id' => $contestInfo['id'],
                'works_id' => $this->request->works_id,
                'yyy' => date('Y'),
                'mmm' => date('m'),
                'ddd' => date('d'),
                'date' => date('Y-m-d'),
                'user_id' => $user_id,
                'terminal' => 'wx',
            ]);

            DB::commit();
            return $this->returnApi(200, "投票成功", true, ['user_vote_num' => $user_vote_num + 1]); //返回用户已投票数量
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "投票失败");
        }
    }

    /**
     * 撤销、删除作品
     * @param token  用户token
     * @param works_id 作品id
     * @param status 状态 4.已撤销， 5已删除 
     */
    public function  worksCancelAndDel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_works_cancel_del')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        if ($this->request->status != 4 && $this->request->status != 5) {
            return $this->returnApi(201, "参数错误");
        }
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];

        $result = $this->worksModel->find($this->request->works_id);
        if (empty($result)) {
            return $this->returnApi(201, "参数错误");
        }
        if ($result['user_id'] != $user_id) {
            return $this->returnApi(201, "网络错误");
        }
        if ($this->request->status == 4 &&  $result['status'] != 3) {
            return $this->returnApi(201, "此状态不允许撤销");
        } elseif ($this->request->status == 5 &&  ($result['status'] != 4 && $result['status'] != 2)) {
            return $this->returnApi(201, "此状态不允许删除");
        }
        DB::beginTransaction();
        try {
            $result->status = $this->request->status;
            $res = $result->save();

            /*消息推送*/
            $status_msg = $this->request->status == 5 ? '删除' : '撤销';
            $system_id = $this->systemAdd($status_msg . '在线投票,投稿的作品', $user_id, $account_id, 16, intval($result->id), '作品：【' . $result->title . '】' . $status_msg . '成功');

            /**执行积分规则 */  //撤销才执行，因为删除的作品，必须是撤销的
            // if (config('other.is_need_score') === true) {
            //     if (!empty($result->score) && $this->request->status == 4) {
            //         $scoreRuleObj = new ScoreRuleController();
            //         $score_msg = $scoreRuleObj->getScoreMsg($result->score);
            //         $scoreRuleObj->scoreReturn($this->score_type, $result->score, $result->user_id, $result->account_id, '在线投票撤销作品，' . $score_msg . ' ' . abs($result->score) . ' 积分', $system_id, '在线投票撤销作品');
            //     }
            // }

            DB::commit();
            return $this->returnApi(200, $this->request->status == 5 ? "删除成功" : '撤销成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $this->request->status == 5 ? "删除失败" : '撤销失败');
        }
    }


    /**
     * 上传作品
     * @param token 用户token
     * @param unit_id 单位id
     * @param con_id 大赛id
     * @param username 用户名
     * @param tel 用户电话
     * @param id_card 身份证号码
     * @param unit 单位、学校
     * @param wechat_number 微信号
     * @param reader_id 读者证号
     * @param adviser 指导老师
     * @param adviser_tel 指导老师联系方式
     * @param title 标题
     * @param type_id 类型id
     * @param img 作品图片地址 node=1
     * @param content 作品图片地址 node=2
     * @param voice 作品音频地址 node=3
     * @param voice_name 音频名称
     * @param video 视频资源 node=4
     * @param video_name 作品名称
     * @param intro 作品简介
     * @param cover 作品封面
     * @param width 宽度
     * @param height 高度
     */
    public function worksAdd()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_works_add')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        //作品必须存在一个
        if (empty($this->request->img) && empty($this->request->content) && empty($this->request->voice) && empty($this->request->video)) {
            return $this->returnApi(201, "上传作品不能为空");
        }


        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];

        /*检查是否违规*/
        $validateModel = new UserViolate();
        $isViolate = $validateModel->checkIsViolate($user_id, 'contest');
        if ($isViolate) {
            return $this->returnApi(201, '已达到违规次数上限,不能上传作品');
        }


        $contestInfo = $this->model->where('is_del', 1)->find($this->request->con_id);
        if ($contestInfo['node'] == 2 && empty($this->request->unit_id)) {
            return $this->returnApi(201, "单位id不能为空");
        }


        if (empty($contestInfo)) {
            return $this->returnApi(201, "大赛不存在，不允许投稿");
        }
        if ($contestInfo['con_start_time'] > date('Y-m-d H:i:s')) {
            return $this->returnApi(201, "投稿未开始，暂不允许投稿");
        }
        if ($contestInfo['con_end_time'] < date('Y-m-d H:i:s')) {
            return $this->returnApi(201, "投稿已结束，不允许投稿");
        }

        $contestActivityTypeInfo = ContestActivityType::where('is_del', 1)->find($this->request->type_id);
        if (empty($contestActivityTypeInfo)) {
            return $this->returnApi(201, "大赛类型不存在，不允许投稿");
        }

        //已上传数量
        if ($contestActivityTypeInfo['limit_num'] !== 0) {
            $have_number = $this->worksModel->getUserWorksNumberByTypeId($this->request->con_id, $user_id, $this->request->type_id);
            if ($contestActivityTypeInfo['limit_num'] <= $have_number) {
                return $this->returnApi(201, "此类作品，您上传的数量已达到上限，请在个人投稿记录中查看");
            }
        }

        //判断积分是否满足条件 后台审核统一增加
        // if (config('other.is_need_score') === true  && $contestInfo->is_reader == 1) {
        //     $scoreRuleObj = new ScoreRuleController();
        //     $score_status = $scoreRuleObj->checkScoreStatus($this->score_type, $user_id, $account_id);
        //     if ($score_status['code'] == 202) return $this->returnApi(202, $score_status['msg']);
        // }


        DB::beginTransaction();
        try {
            //判断参数
            if (!empty($contestInfo->real_info)) {
                $real_info = explode('|', $contestInfo->real_info);
                $this->model->checkApplyParam($real_info, $this->request->all());
            }

            $serial_number = $this->worksModel->getSerialNumber($contestActivityTypeInfo['letter']);
            $this->request->merge([
                'serial_number' => $serial_number,
                'user_id' => $user_id,
                'account_id' => $account_id,
                'score' => !empty($score_status['score_info']['score']) ? $score_status['score_info']['score'] : 0
            ]);
            $this->worksModel->add($this->request->all());

            /*消息推送*/
            $system_id = $this->systemAdd('线上大赛投稿作品', $user_id, $account_id, 15, intval($this->worksModel->id), '线上大赛：【' . $contestInfo->title . '】投稿成功，等待后台管理员审核！');

            // if (config('other.is_need_score') === true  && $contestInfo->is_reader == 1) {
            //     if ($score_status['code'] == 200) {
            //         $scoreRuleObj->scoreChange($score_status, $user_id, $account_id, $system_id); //添加积分消息
            //     }
            // }

            DB::commit();
            return $this->returnApi(200, "投稿成功，等待后台管理员审核！", true); //返回用户已投稿数量
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 修改作品
     * @param token 用户token
     * @param unit_id 单位id
     * @param works_id 作品id
     * @param con_id 大赛id
     * @param username 用户名
     * @param tel 用户电话
     * @param id_card 身份证号码
     * @param unit 用户单位/学校
     * @param wechat_number 微信号
     * @param reader_id 读者证号
     * @param adviser 指导老师
     * @param adviser_tel 指导老师联系方式
     * @param title 标题
     * @param type_id 类型id
     * @param img 作品图片地址 node=1
     * @param content 作品图片地址 node=2
     * @param voice 作品音频地址 node=3
     * @param voice_name 音频名称
     * @param video 视频资源 node=4
     * @param video_name 作品名称
     * @param intro 作品简介
     * @param cover 作品封面
     * @param width 宽度
     * @param height 高度
     */
    public function worksChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_works_change')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        //作品必须存在一个
        if (empty($this->request->img) && empty($this->request->content) && empty($this->request->voice) && empty($this->request->video)) {
            return $this->returnApi(201, "上传作品不能为空");
        }
        $res = $this->worksModel->find($this->request->works_id);
        if (empty($res)) {
            return $this->returnApi(201, "参数错误");
        }

        // Log::error($_POST);

        if ($res['status'] != 4 && $res['status'] != 2) {
            return $this->returnApi(202, "请先撤销在进行修改！");
        }

        $user_id = $this->request->user_info['id'];
        $contestInfo = $this->model->where('is_del', 1)->find($this->request->con_id);

        if ($contestInfo['node'] == 2 && empty($this->request->unit_id)) {
            return $this->returnApi(201, "单位id不能为空");
        }


        if (empty($contestInfo)) {
            return $this->returnApi(201, "大赛不存在，不允许投稿");
        }
        if ($contestInfo['con_start_time'] > date('Y-m-d H:i:s')) {
            return $this->returnApi(201, "投稿未开始，暂不允许投稿");
        }
        if ($contestInfo['con_end_time'] < date('Y-m-d H:i:s')) {
            return $this->returnApi(201, "投稿已结束，不允许投稿");
        }

        $contestActivityTypeInfo = ContestActivityType::where('is_del', 1)->find($this->request->type_id);
        if (empty($contestActivityTypeInfo)) {
            return $this->returnApi(201, "大赛类型不存在，不允许投稿");
        }

        //已上传数量
        if ($contestActivityTypeInfo['limit_num'] !== 0) {
            $have_number = $this->worksModel->getUserWorksNumberByTypeId($this->request->con_id, $user_id, $this->request->type_id);
            if ($contestActivityTypeInfo['limit_num'] <= $have_number - 1) {
                return $this->returnApi(201, "此类作品，您上传的数量已达到上线，请在个人投稿记录中查看");
            }
        }

        DB::beginTransaction();
        try {
            //判断参数
            if (!empty($contestInfo->real_info)) {
                $real_info = explode('|', $contestInfo->real_info);
                $this->model->checkApplyParam($real_info, $this->request->all());
            }

            $data = $this->request->all();
            $data['id'] = $data['works_id'];
            $data['status'] = 3;
            unset($data['works_id']);
            $this->worksModel->change($data);

            DB::commit();
            return $this->returnApi(200, "修改成功，等待后台管理员审核！", true); //返回用户已投稿数量
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }
}
